package com.pedometer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class PedometerActivity extends Activity{
	
	TextView stepsText;
    TextView orientationText;
    TextView distanceText;
    TextView averageSpeedText;    
    private Button exitButton;
    private Button startServiceButton;
    private Button stopServiceButton;
    
    protected SensorInterface sensorInterface;
	private Intent myIntent;
	private Handler mHandler;
    
    protected boolean isBound = false;    //Will be used for checking the status of the Service
    protected float orientation=0;
    protected int steps=0;
    protected float distance=0;
    protected float averageSpeed=0;    
    
    
    public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);  
		
		stepsText = (TextView) findViewById(R.id.steps_text);
		orientationText = (TextView) findViewById(R.id.orientation_text);
		distanceText = (TextView) findViewById(R.id.distance_text);
		averageSpeedText = (TextView) findViewById(R.id.avg_speed_text);		
		
		startServiceButton = (Button) findViewById(R.id.start_service_button);
        startServiceButton.setOnClickListener(startServiceButtonListener);
        stopServiceButton = (Button) findViewById(R.id.stop_service_button);
        stopServiceButton.setOnClickListener(stopServiceButtonListener);
        exitButton = (Button) findViewById(R.id.exit_button);
        exitButton.setOnClickListener(exitButtonListener);
        
        myIntent = new Intent(this, SensorService.class); //to launch/communicate with the background Service
        mHandler = new Handler();  //A Handler allows us to process Runnable objects associated with this thread
    }
    
    public void onResume(){
    	super.onResume();    	
    	if(isBound)			
        	doBindService();        
    }
        
    public void onPause(){
    	super.onPause();    	
    	if(isBound)
        	doUnbindService();
    }
    
    void doBindService() {  
    	// Establish a connection with the service.  We use an explicit
    	// class name because we want a specific service implementation that
    	// we know will be running in our own process (and thus won't be
    	// supporting component replacement by other applications).		
		bindService(myIntent, myConnection, Context.BIND_AUTO_CREATE);
		//isBound = true;				
	}
    
    void doUnbindService() {    	
    	unbindService(myConnection);
    	//isBound = false;    	
	}
    
    private ServiceConnection myConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service.  Because we have bound to a explicit
            // service that we know is running in our own process, we can
            // cast its IBinder to a concrete class and directly access it.
        	sensorInterface = SensorInterface.Stub.asInterface(service);
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
            sensorInterface = null;
        }
    };    
 
    private final Runnable timedTask = new Runnable(){
    	// timedTask, represents a command that can be executed
        // Often used to run code in a different Thread
    	public void run() {
    		update();    	
    		mHandler.postDelayed(timedTask, 100); //update() will be called every 100 milliseconds
  	  }
    };
    
  	public void update() {
  		if(sensorInterface != null){
  			try {
  				steps = sensorInterface.getSteps();
  				orientation = sensorInterface.getOrientation();
  				distance = sensorInterface.getDistance();
  				averageSpeed = sensorInterface.getAverageSpeed();
  			} catch (RemoteException e) {
  				e.printStackTrace();
  			}
  		}
  	    	
  		stepsText.setText(Integer.toString(steps)); 
  		orientationText.setText(Float.toString(orientation));
  		distanceText.setText(Float.toString(distance));
  		averageSpeedText.setText(Float.toString(averageSpeed));
  	} 
   
  	
  	private OnClickListener startServiceButtonListener = new OnClickListener() {
        public void onClick(View v) {     

        	if(isBound){
        		Toast toast = Toast.makeText(getApplicationContext(), 
    					"Service already running.", Toast.LENGTH_SHORT);
    			toast.show();       		
        	}
        	else{        		
        		startService(myIntent);
        		isBound = true;
        		doBindService();
        		mHandler.removeCallbacks(timedTask); //Remove any pending posts of Runnable timedTask
                mHandler.post(timedTask);	//The runnable will be run on the thread to which this handler is attached
        	}
        }
  	};
  	
  	private OnClickListener stopServiceButtonListener = new OnClickListener() {
        public void onClick(View v) {

        	if(isBound){
        		doUnbindService();
        		mHandler.removeCallbacks(timedTask); //Remove any pending posts of Runnable timedTask 
        		stopService(myIntent);
        		isBound = false;
        		
        	} else {
        		Toast toast = Toast.makeText(getApplicationContext(), 
    					"Service already stopped.", Toast.LENGTH_SHORT);
    			toast.show();
        	}
        }
    };
    
    private OnClickListener exitButtonListener = new OnClickListener() {
        public void onClick(View v) {
        	finish();
        }
    };    
           
    @Override
    public void onDestroy(){
    	super.onDestroy();
    	stopService(myIntent);
    }     
       
}